package com.weixing.core.service.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.alibaba.fastjson.JSON;
import com.weixing.core.entity.WeatherInfo;
import com.weixing.core.service.WeatherService;
import com.weixing.core.util.WeixinUtil;
import com.weixing.core.util.impl.WeiXinUtilForImpl;

/**
 * 天气服务接口实现
 * 
 * @author Fu Dongwei
 * @Date 2015-02-05
 * @version 1.0
 */
public class WeatherServiceForImpl implements WeatherService {

	private static final Log LOGGER = LogFactory
			.getLog(WeatherServiceForImpl.class);

	// 根据城市名获取气象信息字符串
	@Override
	public String getWeatherInfo(String city) {
		// TODO Auto-generated method stub
		// String url = WeatherService.WEATHERURL.replace("CITYID",
		// "101210401");
		WeixinUtil weixinUtil = new WeiXinUtilForImpl();
		String url = WeatherService.WEATHERFIVEURL.replace("WEAID",
				GetCityID(city));
		String weatherInfoStr = weixinUtil.httpRequest(url);
		weatherInfoStr = weatherInfoStr.substring(
				weatherInfoStr.indexOf("result") + 8,
				weatherInfoStr.length() - 1);
		List<WeatherInfo> weatherInfos = JSON.parseArray(weatherInfoStr,
				WeatherInfo.class);
		// 输出结果
		StringBuffer result = new StringBuffer();
		if (weatherInfos != null && !weatherInfos.isEmpty()) {
			// 地区
			result.append("当前地区：").append(city).append("\n");
			int i = 0;
			for (WeatherInfo weatherinfo : weatherInfos) {
				result.append("日期：" + weatherinfo.getDays()).append("\n");
				result.append(weatherinfo.getWeek()).append("\n");
				result.append("天气情况：" + weatherinfo.getWeather()).append("\n");
				result.append("温度:" + weatherinfo.getTemperature())
						.append("\n");
				i++;
				if (i < 3) {
					result.append("\n\n");
				} else {
					break;
				}
			}
			if (weatherInfos.isEmpty()) {
				result.append("系统没有查询到天气情况！\n");
			}
		}
		return result.toString();
	}

	// 根据城市名获取城市ID
	private String GetCityID(String cityname) {
		WeixinUtil weixinUtil = new WeiXinUtilForImpl();
		String cityStr = weixinUtil.httpRequest(WeatherService.WEATHERCITYURL);
		int index = cityStr.indexOf("result", 0);
		cityStr = cityStr.substring(index + 8, cityStr.length() - 1);
		String result = cityStr;
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> citymaps = objectMapper.readValue(cityStr,
					Map.class);
			Set<String> key = citymaps.keySet();
			Iterator<String> iter = key.iterator();
			while (iter.hasNext()) {
				String field = iter.next();
				Object object = citymaps.get(field);
				result = object.toString();
				if (result.contains(cityname)) {
					break;
				}
			}
			result = result.substring(result.indexOf("weaid") + 6,
					result.indexOf(','));
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			LOGGER.error("JSON转换异常！" + e.getMessage());
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			LOGGER.error("JSON映射异常！" + e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			LOGGER.error("IO异常！" + e.getMessage());
		}
		return result;
	}
}
